import { DOWNLOAD_PATH, fs, path, notification } from "@/global";
import store from "@/store";
import { request, config } from "@/global";

const downloadEnum = {
  DOWNLOAD_QUEUE_STOP: "DOWNLOAD_QUEUE_STOP",
  DOWNLOAD_QUEUE_RUNNING: "DOWNLOAD_QUEUE_RUNNING"
};

let downloadStatus = downloadEnum.DOWNLOAD_QUEUE_STOP;

let requestInstance;

const createDirIfAbsent = function() {
  if (!fs.existsSync(DOWNLOAD_PATH)) {
    fs.mkdirSync(DOWNLOAD_PATH);
  }
};

const startDownloadQueue = async function() {
  let element = store.getters.world.userInfo.downloadQueue[0];
  let queue = store.getters.world.userInfo.downloadQueue;
  if (element == null) {
    notification("下载队列为空哦！");
    return;
  }
  if (downloadStatus === downloadEnum.DOWNLOAD_QUEUE_RUNNING) {
    notification("下载队列已经开始了");
    return;
  }
  downloadStatus = downloadEnum.DOWNLOAD_QUEUE_RUNNING;
  createDirIfAbsent();
  while (
    queue.length > 0 &&
    downloadStatus === downloadEnum.DOWNLOAD_QUEUE_RUNNING
  ) {
    let filepath = path.join(DOWNLOAD_PATH, element.filename);
    let fileSize = 0;
    if (fs.existsSync(filepath)) {
      fileSize = fs.statSync(filepath).size;
    }
    await downloadHandler(element, fileSize, filepath);
    element = store.getters.world.userInfo.downloadQueue[0];
  }
  downloadStatus = downloadEnum.DOWNLOAD_QUEUE_STOP;
};

const downloadHandler = function(element, fileSize, filepath) {
  return new Promise((resolve, reject) => {
    let params = {
      method: "post",
      url:
        config.baseURL +
        "/file/download/" +
        element.fileId +
        "/" +
        store.getters.token
    };
    if (fileSize > 0) {
      params.headers = {};
      params.headers["Range"] = "bytes=" + fileSize + "-";
    }

    let out = fs.createWriteStream(filepath, {
      flags: fileSize === 0 ? "w" : "a",
      start: fileSize
    });
    requestInstance = request(params);
    requestInstance.pipe(out);
    //请求后才能拿到文件大小，首次下载设置文件长度，用于计算下载进度
    requestInstance.on("response", resp => {
      let contentLength = resp.headers["content-length"];
      //文件已下载完
      if (contentLength == 0) {
        afterDownload(element);
        resolve();
      }
      if (fileSize === 0) {
        store.commit("SET_DOWNLOAD_FIRST_ELEMENT_FILE_SIZE", contentLength);
      }
    });
    requestInstance.on("data", chunk => {
      //更新下载进度
      store.commit(
        "UPDATE_DOWNLOAD_QUEUE_FIRST_ELEMENT_UPLOADED_DOWNLOADED",
        chunk.length
      );
    });

    requestInstance.on("end", () => {
      //字符串和数字比较
      if (fs.statSync(filepath).size == element.fileSize) {
        afterDownload(element);
        resolve();
      }
    });
    requestInstance.on("error", err => reject(err));
  });
};

const stopDownloadQueue = function() {
  if (downloadStatus === downloadEnum.DOWNLOAD_QUEUE_STOP) {
    notification("下载队列已经暂停了");
    return;
  }
  downloadStatus = downloadEnum.DOWNLOAD_QUEUE_STOP;
  requestInstance.abort();
  notification("下载队列已暂停");
};

const afterDownload = function(finishElement) {
  notification("有一个任务下载完成");
  store.commit("OFFER_TRANS_HISTORY", finishElement);
  store.commit("DELETE_ELEMENT_FROM_DOWNLOAD_QUEUE", finishElement);
};

const offerDownloadQueue = function(
  fileId,
  filename,
  downloaded = 0,
  fileSize = -1
) {
  store.commit("OFFER_DOWNLOAD_QUEUE", {
    fileId,
    filename,
    downloaded,
    fileSize
  });
  notification("一个新的下载任务添加成功");
};

export {
  startDownloadQueue,
  downloadStatus,
  downloadEnum,
  stopDownloadQueue,
  offerDownloadQueue
};
